import { defineStore } from "pinia";
import { computed, ref } from "vue";
import axios from "../axios";

export const useAuthStore = defineStore('auth', () => {
    const token = ref<string | null>(localStorage.getItem('token'))

    const isAuthenticated = computed(() => !!token.value)

    // 登录
    const login = async (username: string, password: string) => {
        try {
            // 发送登录请求
            const resp = await axios.post('/auth/login', { username, password })
            token.value = resp.data.token
            localStorage.setItem('token', token.value || '')
        } catch (error) {
            console.log('login error:', error)
        }
    }

    // 注册
    const registry = async (username: string, password: string) => {
        try {
            // 发送登录请求
            const resp = await axios.post('/auth/register', { username, password })
            token.value = resp.data.token
            console.log('registry resp:', resp.data)
            localStorage.setItem('token', token.value || '')
        } catch (error) {
            console.log('registry error:', error)
        }
    }

    // 退出登录
    const logout = () => {
        token.value = null;
        localStorage.removeItem('token')
    }

    return {
        token,
        login,
        registry,
        logout,
        isAuthenticated
    }


})